<template>
	<view style="user-select: text;">
		<sunMenu :id="menuId"></sunMenu>
		<view style="padding: 10rpx;">
		</view>
		<view class="content-container">
			<view class="content-wrapper">
				<!-- 赛事介绍 -->
				<view class="race-intro">
					<view class="title">賽事資訊</view>
					<view class="info">
						<view>{{info.activeContent}}</view>
						<view>活動宗旨：{{info.activeZz}}</view>
						<view>活動時間：{{info.activeTime}}</view>
						<view>活動地點：{{info.address}}</view>
					</view>
				</view>
				<!-- 比赛项目表格 -->
				<view class="race-groups">
					<view class="title">比賽項目</view>
					<scroll-view scroll-x>
						<view class="table">

							<scroll-view scroll-x style="width: 100%;">
								<view class="table-header">
									<view class="col" :style="{ width: firstColumnWidth }">組別</view>
									<view class="col" :style="{ width: raceColumnWidth }" v-for="race in uniqueRaces"
										:key="race.name">
										<view>
											<view>
												{{race.name}}
											</view>
											<view>
												({{race.distance}}KM)
											</view>
										</view>
									</view>
								</view>
								<!-- 組別 (feeType=0) -->
								<view v-for="group in getGroupsByFeeType('0')" :key="group.groupName" class="table-row">
									<view class="col" :style="{ width: firstColumnWidth }">{{group.groupName}}</view>
									<view class="col" :style="{ width: raceColumnWidth }" v-for="race in uniqueRaces"
										:key="race.name" v-html="getFeeValue(group.items, race.name)">
									</view>
								</view>
								<!-- 報名資訊 -->
								<view class="section-title">
									<!-- <view class="col" :style="{ width: '100%' }">報名資訊</view> -->
								</view>
								<view v-for="group in getGroupsByFeeType('1')" :key="group.groupName" class="table-row">
									<view class="col" :style="{ width: firstColumnWidth }">{{group.groupName}}</view>
									<template v-if="shouldMergeColumns(group.items)">
										<!-- mergedColumnsWidth  width: ${100 - parseInt(this.firstColumnWidth)}%-->
										<view class="col"
											:style="{width:mergedColumnsWidth(uniqueRaces.length,li.count)}"
											v-for="li in getMergedCells(group.items)">
											<!-- {{getFeeValue(group.items, uniqueRaces[0].name)}} -->
											{{li.value}}
										</view>
									</template>
									<template v-else>
										<view class="col" :style="{ width: raceColumnWidth }"
											v-for="race in uniqueRaces" :key="race.name"
											v-html="getFeeValue(group.items, race.name)">
										</view>
									</template>
								</view>
								<!-- 活動前物資 -->
								<view class="section-title">
									<!-- <view class="col" :style="{ width: '100%' }">活動前物資 (郵寄)</view> -->
								</view>
								<view v-for="group in getGroupsByFeeType('2')" :key="group.groupName" class="table-row">
									<view class="col" :style="{ width: firstColumnWidth }">{{group.groupName}}</view>
									<view class="col" :style="{ width: raceColumnWidth }" v-for="race in uniqueRaces"
										:key="race.name">
										<view>
											<view v-if="getFeeValue(group.items, race.name) === 'true'"
												class="check-circle">✓
											</view>
											<view v-else-if="getFeeValue(group.items, race.name) === 'false'"
												class="cross-circle">✕</view>
											<template v-else>{{getFeeValue(group.items, race.name)}}</template>
										</view>
									</view>
								</view>

								<!-- 完賽禮 -->
								<view class="section-title">
									<!-- <view class="col" :style="{ width: '100%' }">完賽禮 (現場領取)</view> -->
								</view>
								<view v-for="group in getGroupsByFeeType('3')" :key="group.groupName" class="table-row">
									<view class="col" :style="{ width: firstColumnWidth }">{{group.groupName}}</view>
									<view class="col" :style="{ width: raceColumnWidth }" v-for="race in uniqueRaces"
										:key="race.name">
										<view>
											<view v-if="getFeeValue(group.items, race.name) === 'true'"
												class="check-circle">✓
											</view>
											<view v-else-if="getFeeValue(group.items, race.name) === 'false'"
												class="cross-circle">✕</view>
											<template v-else>{{getFeeValue(group.items, race.name)}}</template>
										</view>
									</view>
								</view>
								<view v-for="group in getGroupsByFeeType('4')" :key="group.groupName" class="table-row">
									<view class="col" :style="{ width: firstColumnWidth }">{{group.groupName}}</view>
									<template v-if="shouldMergeColumns(group.items)">
										<!-- mergedColumnsWidth  width: ${100 - parseInt(this.firstColumnWidth)}%-->
										<view class="col"
											:style="{width:`${  mergedColumnsWidth()/uniqueRaces.length*li.count  }%`}"
											v-for="li in getMergedCells(group.items)">
											<!-- {{getFeeValue(group.items, uniqueRaces[0].name)}} -->
											{{li.value}}
										</view>
									</template>
									<template v-else>
										<view class="col" :style="{ width: raceColumnWidth }"
											v-for="race in uniqueRaces" :key="race.name"
											v-html="getFeeValue(group.items, race.name)">
										</view>
									</template>
								</view>
							</scroll-view>
						</view>
					</scroll-view>

				</view>

				<!-- 活动流程 -->
				<view class="schedule" style="margin-bottom: 60px;">
					<view class="title">活動流程</view>
					<view class="timeline">
						<view class="timeline-header">
							<view class="header-item">時間</view>
							<view class="header-item">活動內容</view>
						</view>
						<view v-for="(item, index) in apList" :key="index" class="time-item">
							<view class="time">{{item.acKey}}</view>
							<view class="event">{{item.acValue}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="signup-button-container">
			<button class="signup-button" :class="{ disabled: !canSignup }" @click="handleSignup">立即報名</button>
		</view>
		<terms-dialog :visible.sync="showTerms" @confirm="handleTermsConfirm" 
		@TeamConfirm="TeamConfirm"
		
		@cancel="handleTermsCancel" />
		<view class="footer">
			<text class="footer-text">© 2025 夏璽玥網路有限公司 版權所有 XIA AKOYA INC. All Rights Reserved. 統一編號90370186</text>
			 
		</view>
		<view style="height: 150rpx;"></view>
	</view>
</template>

<script>
	import sunMenu from '../components/sun-menu/sun-menu.vue'
	import {
		getProjectData
	} from '@/api/api.js'
	import termsDialog from '../components/terms-dialog/terms-dialog.vue'
	export default {
		components: {
			sunMenu,
			termsDialog
		},
		data() {
			return {
				apList: [],
				pdList: [],
				info: {},
				showTerms: false,
				menuId: null
			}
		},
		onLoad(op) {
			this.menuId = op.id;
			uni.setStorageSync("activeId", op.id)
			this.getProjectData(op.id)
			uni.setStorageSync("activeTime", op.activeTime)
		},
		computed: {
			// 添加新的算属性来获取唯一的比赛项目
			uniqueRaces() {
				const races = new Set();
				const result = [];
				this.pdList.forEach(item => {
					const key = item.name + item.distance;
					if (!races.has(key)) {
						races.add(key);
						result.push({
							name: item.name,
							distance: item.distance
						});
					}
				});
				return result;
			},

			// 判断是否可以报名
			canSignup() {
				if (!this.info.startTime || !this.info.endTime) return false;
				const now = new Date();
				const startTime = new Date(this.info.startTime);
				const endTime = new Date(this.info.endTime);
				return now >= startTime && now <= endTime;
			},

			// 将pdList按groupName分组
			groupedPdList() {
				const groups = {};
				this.pdList.forEach(item => {
					if (!groups[item.groupName]) {
						groups[item.groupName] = {
							groupName: item.groupName,
							items: []
						};
					}
					groups[item.groupName].items.push(item);
				});
				return Object.values(groups);
			},
			firstColumnWidth() {
				return '30%'; // You can adjust this value as needed
			},
			raceColumnWidth() {
				let isPC = true
				const userAgent = navigator.userAgent.toLowerCase();
				if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(userAgent)) {
					isPC = false
				} 
				let columnWidth = this.firstColumnWidth
				let maxLength = 0
				for (let i = 0; i < this.uniqueRaces.length; i++) {
					let num = this.uniqueRaces[i].name.length + this.uniqueRaces[i].distance.length
					if (maxLength < num) {
						maxLength = num
					}
				}
				const remainingWidth = 100 - parseInt(columnWidth);
				if (maxLength >= 6&&!isPC) {
					let re = (remainingWidth / this.uniqueRaces.length) + maxLength * 2
					return re + '%';
				} else {
					let re = (remainingWidth / this.uniqueRaces.length)
					return re + '%';
				}
			},

		},
		methods: {
			mergedColumnsWidth(length, count) {
				let isPC = true
				const userAgent = navigator.userAgent.toLowerCase();
				if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(userAgent)) {
					isPC = false
				}
				let maxLength = 0
				for (let i = 0; i < this.uniqueRaces.length; i++) {
					let num = this.uniqueRaces[i].name.length + this.uniqueRaces[i].distance.length
					if (maxLength < num) {
						maxLength = num
					}
				}
				let columnWidth = this.firstColumnWidth
				const remainingWidth = 100 - parseInt(columnWidth);
				if (maxLength >= 6&&!isPC) {
					let re = ((remainingWidth / length) + (maxLength * 2)) * count
					return re + '%';
				} else {
					let re = ((remainingWidth / length)) * count
					return re + '%';
				} 
			},
			getProjectData(id) {
				getProjectData(id).then(res => {
					this.pdList = res.data.pdList
					this.apList = res.data.apList
					this.info = res.data.info
				})
			},
			// 获取指定组别的值
			getFeeValue(items, name) {
				const item = items.find(i => i.name === name);
				if (!item) return '';
				// 根据feeType返回不同格式的值
				switch (item.feeType) {
					case '0': // 费用
						return `NTD ${item.feeValue}`;
					case '1': // 名
						return `${item.feeValue}`;
					case '2': // 纪念衣
					case '3': // 完赛奖牌
						return item.feeValue
					default:
						return item.feeValue;
				}
			},
			// 添加新方法
			shouldMergeColumns(items) {
				if (!items || items.length <= 1) return false;
				const values = items.map(item => this.getFeeValue([item], item.name));
				// 检查相邻单元格是否有相同的值
				for (let i = 0; i < values.length - 1; i++) {
					if (values[i] === values[i + 1]) {
						return true; // 如果相邻单元格相同，则返回 true
					}
				}
				return false; // 否则返回 false
			},
			// 新增方法来处理合并单元格的逻辑
			getMergedCells(items) {
				const mergedCells = [];
				// const values1 = items.map(item => this.getFeeValue([item], item.name));
				let values = []
				for (let i = 0; i < this.uniqueRaces.length; i++) {
					for (let h = 0; h < items.length; h++) {
						if (this.uniqueRaces[i].name == items[h].name) {
							values.push(items[h].feeValue)
						}
					}
				}
				for (let i = 0; i < values.length; i++) {
					if (i > 0 && values[i] === values[i - 1]) {
						// 如果当前值与前一个值相同，标记为合并
						mergedCells[mergedCells.length - 1].count++;
					} else {
						// 否则，添加新的单元格
						mergedCells.push({
							value: values[i],
							count: 1
						});
					}
				}
				return mergedCells;
			},
			// 添加新方法
			getGroupsByFeeType(feeType) {
				return this.groupedPdList.filter(group =>
					group.items.some(item => item.feeType === feeType)
				);
			},
			handleSignup() {
				if (!this.canSignup) {
					const now = new Date();
					const startTime = new Date(this.info.startTime);
					const endTime = new Date(this.info.endTime);
					
					let message = '';
					if (now < startTime) {
						message = '報名尚未開始';
					} else if (now > endTime) {
						message = '報名已經截止';
					}
					
					uni.showToast({
						title: message,
						icon: 'none',
						duration: 2000
					});
					return;
				}
				
				if (this.$store.state.user.token == "") {
					uni.showModal({
						title: '提示',
						content: '是否登錄後再報名',
						confirmText: '去登錄',
						cancelText: '不登錄直接報名',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/myLogin'
								});
							} else {
								this.showTerms = true;
							}
						}
					});
					return;
				}
				this.showTerms = true;
			},
			handleTermsConfirm() {
				uni.navigateTo({
					url: '/pages/signup?id=' + this.info.id
				});
			},
			TeamConfirm() {
				uni.navigateTo({
					url: '/pages/signupTeam?id=' + this.info.id
				});
			},
			handleTermsCancel() {
				this.showTerms = false;
			}
		}
	}
</script>

<style>
	.race-intro,
	.race-groups,
	.schedule {
		padding: 40rpx;
		background: #ffffff;
		border-radius: 12px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.03);
		margin: 24rpx;
	}

	.title {
		font-size: 18px;
		font-weight: 600;
		margin-bottom: 15px;
		color: #2c3e50;
		position: relative;
		padding-left: 12px;
	}

	.title::before {
		content: '';
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 4px;
		height: 18px;
		background: #81D8D0;
		border-radius: 2px;
	}

	.info {
		line-height: 1.8;
		color: #2c3e50;
	}

	.info view {
		position: relative;
		padding-left: 20px;
	}

	.info view::before {
		content: '•';
		position: absolute;
		left: 5px;
		color: #81D8D0;
	}

	.table {
		border: none;
		border-radius: 12px;
		overflow: hidden;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
	}

	.table-header {
		display: flex;
		background: #81D8D0;
		color: #ffffff;
		min-height: 48px;
		font-weight: 600;
	}

	.table-header .col:first-child {
		background: #81D8D0;
		color: #ffffff !important;
	}

	.table-header .col:not(:first-child) {
		background: linear-gradient(135deg, #81D8D0, #65c6bd);
		color: #ffffff !important;
	}

	.table-header .col {
		color: #ffffff !important;
	}

	.table-row,
	.table-header {
		display: flex;
		border-bottom: 1px solid #eee;
	}

	.table-row:last-child {
		border-bottom: none;
	}

	.col {
		flex-shrink: 0;
		padding: 12px 8px;
		text-align: center;
		border-right: 1px solid #eee;
		display: flex;
		align-items: center;
		justify-content: center;
		word-break: break-word;
		line-height: 1.4;
		min-height: 48px;
		overflow: hidden;
		color: #333;
		background-color: #f8f8f8;
		transition: background-color 0.2s ease;
		font-weight: 600 !important;
	}

	.col:last-child {
		border-right: none;
	}

	.table-row:nth-child(even) {
		background-color: #f9f9f9;
	}

	.table-row:nth-child(odd) {
		background-color: #ffffff;
	}

	.table-row:hover {
		background-color: rgba(129, 216, 208, 0.1);
	}

	/* 第一列样式（标签列） */
	.table-row .col:first-child {
		background-color: #f5f5f5;
		font-weight: 500;
		color: #444;
	}

	/* 特殊值样式 */
	.col .check {
		color: #81D8D0;
		font-size: 20px;
	}

	.col .cross {
		color: #dc3545;
		font-size: 20px;
		opacity: 0.5;
	}

	.merged {
		background-color: rgba(129, 216, 208, 0.03) !important;
	}

	/* 时间线样式优化 */
	.timeline .time-item {
		display: flex;
		padding: 15px 0;
		position: relative;
		align-items: center;
	}

	.timeline .time-item:not(:last-child)::after {
		content: '';
		position: absolute;
		left: 100px;
		top: 50%;
		width: 2px;
		height: calc(100% - 15px);
	}

	.time {
		width: 100px;
		font-weight: 600;
		color: #81D8D0;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: flex-start;
	}

	.time::after {
		content: '';
		position: absolute;
		right: -6px;
		top: 50%;
		transform: translateY(-50%);
		width: 8px;
		height: 8px;
		border-radius: 50%;
		background: #81D8D0;
		box-shadow: 0 0 0 4px rgba(129, 216, 208, 0.2);
	}

	.event {
		width: 50%;
		color: #2c3e50;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.content-container {
		width: 100%;
		display: flex;
		justify-content: center;
		box-sizing: border-box;  
	}

	.content-wrapper {
		width: 100%;
		max-width: 1110px;
		padding-bottom: 120rpx;
	}

	@media screen and (max-width: 768px) {
		.content-wrapper {
			width: 100%;
		}
	}

	.section-title {
		display: flex;
		width: 100%;

	}

	.section-title .col {
		color: #fff;
		font-size: 16px;
		font-weight: 600;
		background-color: #81D8D0;
	}

	/* 添加全局文本选择样式 */
	.content-wrapper {
		user-select: text;
		-webkit-user-select: text;
	}

	.col {
		user-select: text;
		-webkit-user-select: text;
	}

	.info view {
		user-select: text;
		-webkit-user-select: text;
	}

	.event {
		user-select: text;
		-webkit-user-select: text;
	}

	.time {
		user-select: text;
		-webkit-user-select: text;
	}

	.title {
		user-select: text;
		-webkit-user-select: text;
	}

	.check-circle {
		width: 24px;
		height: 24px;
		border-radius: 50%;
		background-color: #4CAF50;
		color: white;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto;
		font-size: 16px;
		line-height: 24px;
		box-shadow: 0 2px 4px rgba(76, 175, 80, 0.2);
		transition: all 0.2s ease;
	}

	.cross-circle {
		width: 24px;
		height: 24px;
		border-radius: 50%;
		background-color: #E0E0E0;
		color: #757575;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto;
		font-size: 16px;
		line-height: 24px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		transition: all 0.2s ease;
	}

	.check-circle:hover {
		transform: scale(1.05);
		box-shadow: 0 3px 6px rgba(76, 175, 80, 0.3);
	}

	.cross-circle:hover {
		transform: scale(1.05);
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
	}

	.signup-button-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background: rgba(255, 255, 255, 0.95);
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
		z-index: 999;
		display: flex;
		justify-content: center;
	}

	@media screen and (min-width: 768px) {
		.signup-button-container {
			width: 100%;
			left: 50%;
			transform: translateX(-50%);
		}
		.content-container { 
			padding: 0 220px;
		}
		
	}

	.signup-button {
		background: #81D8D0;
		color: #ffffff;
		border: none;
		border-radius: 50rpx;
		padding: 6rpx 0;
		font-size: 32rpx;
		font-weight: 600;
		width: 90%;
		margin: 0 auto;
		display: block;
		transition: all 0.3s ease;
	}

	.signup-button.disabled {
		background: #cccccc;
		cursor: not-allowed;
	}

	.signup-button:active {
		transform: scale(0.98);
		background: #65c6bd;
	}

	.signup-button.disabled:active {
		transform: none;
		background: #cccccc;
	}

	.schedule {
		padding: 20px;
		background: #f8f8f8;
		border-radius: 12px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
	}

	.timeline-header {
		display: flex;
		background: #81D8D0;
		/* 蓝色背景 */
		color: #ffffff;
		padding: 10px;
		border-radius: 8px 8px 0 0;
	}

	.header-item {
		flex: 1;
		text-align: center;
		font-weight: bold;
	}

	.time-item {
		display: flex;
		padding: 10px;
		justify-content: space-between;
		/* 使时间和活动内容对齐 */
	}

	.time {
		width: 50%;
		/* 固定宽度 */
		font-weight: 600;
		color: #333;
		text-align: center;
		/* 中心对齐 */
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.event {
		flex: 1;
		padding-left: 20px;
		color: #555;
		text-align: left;
		/* 左对齐 */
	}

	.time-item:last-child {
		border-bottom: none;
		/* 最后一行不显示底部边框 */
	}

	/* 去掉圆点和竖线 */
	.timeline-header::before,
	.timeline-header::after {
		content: none;
	}
</style>